<?php
/** .-------------------------------------------------------------------
* |  Software: [HDPHP framework]
* |      Site: www.hdphp.com
* |-------------------------------------------------------------------
* |    Author: 向军 <2300071698@qq.com>
* |    WeChat: aihoudun
* | Copyright (c) 2012-2019, www.houdunwang.com. All Rights Reserved.
* '-------------------------------------------------------------------*/

namespace system\model;

use hdphp\Model\Model;
use hdphp\qq\org\QC;

class Category extends Model{
	//数据表
	protected $table = "category";

	//允许填充字段
	protected $allowFill = [ ];

	//禁止填充字段
	protected $denyFill = [ ];

	//完整表名
	protected $full = false;

	//自动验证
	protected $validate=[
		//['字段名','验证方法','提示信息',验证条件,验证时间]
        ['cname','required','分类名不能为空',self::MUST_VALIDATE,self::MODEL_BOTH ],
        ['sort','num:1,999','请在1-999之间选择',self::MUST_VALIDATE,self::MODEL_BOTH]
	];

	//自动完成
	protected $auto=[
		//['字段名','处理方法','方法类型',验证条件,验证时机]
	];

	//自动过滤
    protected $filter=[
        //[表单字段名,过滤条件,处理时间]
    ];

	//时间操作,需要表中存在created_at,updated_at字段
	protected $timestamps=false;

    public function store(){
        $Category=new Category();
        $Category['cname']=Q("post.cname");
        $Category['pid']=Q("post.pid");
        $Category['sort']=Q("post.sort");
        $Category['tid']=Q('post.tid');
        return $Category->save();
    }
    //获得所属分类(编辑)
    public function getCateData($cid){
        //首先获得自己的子集
        $cids=$this->getSon(Db::table('category')->get(),$cid);
        //将获取的子集压进$cids里
        $cids[]=$cid;
        //排除自己和自己子集的所有数据
        $data=Db::table('category')->WhereNotIn('cid',$cids)->get();
        //树状结构
        $data=Data::tree($data,'cname');
        //返回数据
        return $data;
    }
    //获得所有子集（递归找子集）
    public function getSon($data,$cid){
        //设置静态数组
        static $temp=[];
        //循环数据
        foreach($data as $v){
            //如果获得$v['pid']==$cid;
            if($v['pid'] == $cid){
                //就将数据存入静态数组中
                $temp[] = $v['cid'];
                //用递归找子集
                $this->getSon($data,$v['cid']);
            }
        }
        //返回数据
        return $temp;
    }
    //分类编辑
    public function edit(){
        $cid = q('cid');
        $Category = Category::find($cid);
        $Category['cname']=Q("post.cname");
        $Category['pid']=Q("post.pid");
        $Category['sort']=Q("post.sort");
        $Category['tid']=Q('post.tid');
        //返回值
        return $Category->save();
    }

}